var api = require('../../config/api.js');
var comm = require("../../utils/comm.js")
var QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js')

var app = getApp()
var qqmapsdk = new QQMapWX({
  key: 'VWEBZ-3NYCW-TXCRD-R66TI-HKPM5-UCBBA' // 必填
});
Page({

  /**
   * 页面的初始数据
   */
  data: {
    toast1Hidden: true,
    modalHidden: true,
    modalHidden2: true,
    notice_str: '',
    // 注册商家根据地址获取经纬度
    shopInfo: {
      id: '',
      deptName: '',
      deptPhone: '',
      logo: ''
    },
    files1: [],
    lng: '',
    lat: ''
  },

  toast1Change: function(e) {
    this.setData({
      toast1Hidden: true
    });
  },

  //表单提交
  formSubmit: function(e) {
    wx.showModal({
      title: '提示',
      content: '是否确认保存信息',
      confirmColor: "#43CBC9",
      success: (res) => {
        wx.showLoading({
          title: '加载中',
        })
        if (res.confirm) {
          console.log('for发生了submit事件，携带数据为：', e.detail.value);

          var reg = /^[0-9a-zA-Z]+$/;
          var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;

          if (e.detail.value.mobile.length == 0) {
            wx.showToast({
              title: "手机号不能为空!",
              icon: 'none',
              duration: 2000
            });
            return false;
          } else if (e.detail.value.mobile.length != 11) {
            wx.showToast({
              title: "手机号长度不正确!",
              icon: 'none',
              duration: 2000
            });
            return false;
          } else if (!myreg.test(e.detail.value.mobile)) {
            wx.showToast({
              title: '手机号格式有误！',
              icon: 'none',
              duration: 2000
            })
            return false;
          } else if (e.detail.value.address.length == 0) {
            wx.showToast({
              title: "地址不能为空!",
              icon: 'none',
              duration: 2000
            });
            return false;
          }
          var logo = this.data.files1 + "";

          this.geocoder(e.detail.value.address);
          this.setData({
            shopInfo: {
              deptPhone: e.detail.value.mobile,
              deptAddress: e.detail.value.address,
              logo: logo,
              id: this.data.id
            }
          })

        } else if (res.cancel) {
          console.log('用户点击取消')
          wx.hideLoading();
        }
      }
    })
  },
  updateShopInfo: function(){
    var that = this;
    console.log(that.data.shopInfo.logo+"------logo");
    wx.request({
      url: api.SalerInfoUpd,
      data: {
        id: that.data.shopInfo.id,
        logo: that.data.shopInfo.logo,
        phone: that.data.shopInfo.deptPhone,
        address: that.data.shopInfo.deptAddress,
        lng: that.data.lng,
        lat: that.data.lat
      },
      method: 'POST',
      header: {
        'Accept': 'application/json',
        'ACCESS-TOKEN': wx.getStorageSync('token')
      },
      success: (res) => {
        wx.showLoading({
          title: '加载中',
        })
        if (res.data.success) {
          wx.showModal({
            title: '提示',
            content: res.data.msg,
            confirmColor: "#43CBC9",
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                console.log('用户点击确定')
                wx.navigateBack({})
              }
            }
          });
          wx.hideLoading();
        }

      }
    })
  },

  formReset: function() {
    wx.showModal({
      title: '提示',
      content: "是否取消本次修改？",
      confirmColor: "#43CBC9",
      showCancel: false,
      success: function(res) {
        if (res.confirm) {
          console.log('用户点击确定')
          wx.navigateBack({})
        }
      }
    });
  },
  geocoder: function (address) {
    var _that = this;
    //调用地址解析接口
        qqmapsdk.geocoder({
      //获取表单传入地址
      address: address, //地址参数，例：固定地址，address: '北京市海淀区彩和坊路海淀西大街74号'
      success: function (res) {//成功后的回调
        console.log(res);
        var res = res.result;
        var latitude = res.location.lat;
        var longitude = res.location.lng;
        _that.setData({
          lat: latitude,
          lng: longitude
        })
        _that.updateShopInfo();

      },
      fail: function (error) {
        console.error(error);
      },
      complete: function (res) {
        console.log(res);
      }
        })
  },

  //弹出确认框  
  modalTap: function(e) {
    this.setData({
      modalHidden: true
    })
  },
  confirm_one: function(e) {
    console.log(e);
    this.setData({
      modalHidden: true,
      toast1Hidden: false,
      notice_str: '提交成功'
    });
  },
  cancel_one: function(e) {
    console.log(e);
    this.setData({
      modalHidden: true,
      toast1Hidden: false,
      notice_str: '取消成功'
    });
  },
  //弹出提示框  
  modalTap2: function(e) {
    this.setData({
      modalHidden2: false
    })
  },
  modalChange2: function(e) {
    this.setData({
      modalHidden2: true
    })
  },

  bindPickerChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index: e.detail.value
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(e) {
    var that = this;
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: api.SalerInfo,
      data: { userId: wx.getStorageSync('userId')},
      method: 'GET',
      header: {
        'Accept': 'application/json',
        'ACCESS-TOKEN': wx.getStorageSync('token')
      },
      success: (res) => {
        if (res.data.success) {
          that.setData({
            deptName: res.data.obj.deptName,
            username: res.data.obj.username,
            mobile: res.data.obj.phone,
            address: res.data.obj.address,
            id: res.data.obj.id,
            files1: res.data.obj.logo == '' ? [] : (res.data.obj.logo).split(",.;")
          });
        }
      }

    })

    var admin = wx.getStorageSync("usertype");
    if (admin == 2) {
      that.setData({
        adminer: '商家',
      })
    } else if (admin == 4) {
      that.setData({
        adminer: '技师',
      })
    }


    wx.hideLoading()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  //选择商品列表图
  chooseImage: function (e) {
    var that = this;
    var len = that.data.files.length;
    if (len < 8) {
      comm.getUploadImg().then(function (link) {
        if (link !== undefined) {
          that.setData({
            files: that.data.files.concat(link)
          });
        } else (
          wx.showToast({
            title: '图片上传失败',
            icon: "none"
          })
        )
      })
    } else {
      wx.showToast({
        title: '图片数量已达到最大限制',
        icon: "none"
      })
    }


  },

  //选择商品主图
  chooseImage1: function (e) {
    var that = this;
    var len = that.data.files1.length;
    if (len < 1) {
      comm.getUploadImg().then(function (link) {
        console.log("----------" + link);
        if (link !== undefined) {
          that.setData({
            files1: that.data.files1.concat(link)
          });
        } else (
          wx.showToast({
            title: '图片上传失败',
            icon: "none"
          })
        )
      })
    } else {
      wx.showToast({
        title: '图片数量已达到最大限制',
        icon: "none"
      })
    }

  },

  //预览商品列表图片
  previewImage: function (e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.files // 需要预览的图片http链接列表
    })
  },

  //预览商品主图片
  previewImage1: function (e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.files1 // 需要预览的图片http链接列表
    })
  },
  //删除列表图片
  deleteImage: function (e) {
    var that = this;
    var files = that.data.files;
    var index = e.currentTarget.dataset.index; //获取当前长按图片下标
    wx.showModal({
      title: '提示',
      content: '确定要删除此图片吗？',
      confirmColor: "#43CBC9",
      success: function (res) {
        if (res.confirm) {
          console.log('点击确定了');
          files.splice(index, 1);
        } else if (res.cancel) {
          console.log('点击取消了');
          return false;
        }
        that.setData({
          files
        });
      }
    })
  },

  //删除主图片
  deleteImage1: function (e) {
    var that = this;
    var files1 = that.data.files1;
    var index = e.currentTarget.dataset.index; //获取当前长按图片下标
    wx.showModal({
      title: '提示',
      content: '确定要删除此图片吗？',
      confirmColor: "#43CBC9",
      success: function (res) {
        if (res.confirm) {
          console.log('点击确定了');
          files1.splice(index, 1);
        } else if (res.cancel) {
          console.log('点击取消了');
          return false;
        }
        that.setData({
          files1
        });
      }
    })
  }
})